// 全局定义一次
layui.config({
    //base: window.location.protocol + '//' + window.location.host + '/public/static/'
    base: APP.STATIC + 'static/'
}).extend({
    xmSelect: '../plugins/layui-xmSelect/xm-select', // 加载 xmSelects(旧版本formSelects)
    //echarts: 'extend/echarts', // 加载 echarts
    //echartsTheme: 'extend/echartsTheme',
    echarts: '../plugins/echarts/echarts', // 加载 echarts
    echartsTheme: '../plugins/echarts/echartsTheme',
    notice: '../plugins/layui-notice/notice',
    viewer: '../plugins/viewer/js/viewer',
    treeTable: '../plugins/layui-treeTable/treeTable',
});

layui.use(['element', 'layer', 'form', 'jquery', 'util', 'notice', 'viewer'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery;

    var util = layui.util;

    var Notice = layui.notice; // 允许别名 toastr
    var Viewer = layui.viewer;


    // 返回顶部
    util.fixbar({
        top: true,
        css: {right: 35, bottom: 15},
        //bgcolor: '#2a96ff !important;display:block;',
        //bgcolor: '#9F9F9F !important; display:block;', // 自定义区块背景色
        //showHeight: 300, // 用于控制出现TOP按钮的滚动条高度临界值。默认：200
        click: function (type) {
            if (type === 'top') {
                $('.layui-body').animate({
                    scrollTop: 0
                }, 200);
            }
        }
    });

    // 关闭 iframe
    $(document).on('click', '.close-btn', function () {
        //parent.layer.close(layer.index);
        var indexLay = parent.layer.getFrameIndex(window.name); // 先得到当前iframe层的索引
        parent.layer.close(indexLay);
    });


    // 清除缓存
    $(document).on('click', '.refresh-btn', function () {
        var index = layer.msg('操作中，请稍候', {icon: 16, time: false, shade: 0.8});

        var url = $(this).attr('data-url');
        $.get(
            url,
            function (res) {
                layer.close(index);
                if (res.code == 1) {
                    //layer.msg('清除缓存成功！3秒后自动刷新页面');
                    COMMON.notice(Notice).success('清除缓存成功！3秒后自动刷新页面');
                    setTimeout('window.location.reload()', 3000);
                }
            }
        );
    });

    // 个人中心
    $(document).on('click', '#view-profile', function () {
        var content = $(this).attr('data-url');
        var index = layer.open({
            title: "个人中心",
            type: 2,
            area: ["600px", "500px"],
            content: content,
            success: function (layero, index) {
                form.render();
            }
        });
    });

    // 修改密码
    $(document).on('click', '#view-reset_password', function () {
        var content = $(this).attr('data-url');
        var index = layer.open({
            title: "修改密码",
            type: 2,
            area: ["600px", "400px"],
            content: content,
            success: function (layero, index) {
                form.render();
            }
        });
    });

    // 批量导出
    $(document).on('click', '#export_csv', function () {
        var _this = $(this);
        var url = $(this).data('url');
        var data = $(this).parents('form').serialize();
        //var data = layui.form.val('searchForm');

        // 方式二
        /*var down_document = {};
        if (typeof(down_document.iframe) == 'undefined') {
            var iframe = document.createElement('iframe');
            down_document.iframe = iframe;
            document.body.appendChild(down_document.iframe);
        }
        down_document.iframe.src = url;
        down_document.iframe.style.display = 'none';*/

        /*
        // 方式三
        var data = {
            'name': name,
            'range_date': range_date
        };

        var frameName = 'downloadFrame_' + new Date().getTime();
        var $iframe = $('<div style="display: none"><iframe name="' + frameName + '" src="about:blank"></iframe></div>');
        var $form = $('<form id="export_form" action="' + url + '" method="post" style="display: none;"></form>');
        // 新窗口导出
        $form.attr('target', '_blank');
        for (var key in data) {
            $form.append('<input type="hidden" name="' + key + '" value="' + data[key] + '" />');
        }
        if ($(document).find('#export_form').length) {
            $(document).find('#export_form').remove();
        }
        $iframe.children().load(function () {
            setTimeout(function () {
                $(this).parent().remove();
            }.bind(this), 3000);
        });

        //$(document.body).append($form);
        //$(document).find('#export_form').submit();

        $iframe.append($form);
        $('body').append($iframe);
        // 提交表单，实现下载
        $form.submit();
        */

        var index = top.layer.msg('数据下载中，请稍候', {icon: 16, time: false, shade: 0.8});
        $.ajax({
            url: url,
            data: data,
            type: "post",
            dataType: "json",
            success: function (res) {
                layer.close(index);
                if (res.code == 1) {
                    // 方式一
                    //document.location = res.data;
                    var iframe = $('<iframe/>', {'src': res.data.url}).hide();
                    _this.append(iframe);
                    layer.msg(res.msg);
                } else {
                    layer.msg(res.msg);
                }
            },
            error: function (data) {
                layer.msg("服务器无响应");
            }
        });
    });

    // iframe页面查看图片
    /*$(document).on('click', '.viewer-photos', function () {
        var src = $(this).find('img').attr('layer-src');

        var img = $('<img />');
        var win_height = $(window).height();
        img.attr('src', src).load(function () {
            var real_width = this.width;
            var real_height = this.height;
            var width = real_width;
            if (width >= 300) {
                width = 300;
                real_height = Math.floor((width / real_width) * real_height);
            }
            if (real_width <= real_height) {
                width = Math.floor(width * (real_width / real_height));
                real_height = Math.floor(real_height * (real_width / real_height));
            }

            var content = '<img src="' + src + '"  width="100%"/>';
            var index = layer.open({
                type: 1,
                title: '',
                closeBtn: 2,
                //zIndex: 99999999,
                area: width + 'px',
                offset: Math.floor((win_height - real_height) / 2) + 'px',
                shadeClose: true,
                content: content
            });
        });
    });*/
    // viewer(jQuery 版本)
    // $(document).find('.layer-photos').viewer({
    //     url: 'layer-src'
    // });
    // viewer(JS 版本)
    var galley = document.getElementsByClassName('viewer-photos');
    if (galley.length > 0) {
        for (var i = 0; i < galley.length; i++) {
            console.log(galley[i]);
            var viewer = new Viewer(galley[i], {
                url: 'layer-src',
                /*title: function (image) {
                    return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')';
                },*/
            });
        }
    }
    $(document).on('click', '.viewer-video', function () {
        var src = $(this).find('video').attr('src');
        var content = '<div class="video-modal"><div class=""><video class="video-box" src="' + src+ '" autoplay="autoplay" controls="controls"></video></div></div>';
        layer.open({
            title: '查看视频',
            type: 1,
            area: ['600px', '500px'],
            content: content
        });
    });
});

var COMMON = function () {
    var viewer = '';
    var viewer_flag = false;

    return {
        notice: function (Notice, config) {
            var $config = {
                closeButton: true,//显示关闭按钮
                debug: false,//是否为调试
                progressBar: true, //是否显示进度条（设置关闭的超时时间进度条）
                positionClass: "toast-top-right",//消息框在页面显示的位置
                showDuration: "300",//显示的时间
                hideDuration: "1000",//消失的时间
                timeOut: "2000",//停留的时间
                extendedTimeOut: "1000",//控制时间
                showEasing: "swing",//显示时的动画缓冲方式
                hideEasing: "linear",//消失时的动画缓冲方式
                iconClass: 'toast-info', // 自定义图标，有内置，如不需要则传空 支持layui内置图标/自定义iconfont类名
                onclick: null, // 点击关闭回调
            };
            $config = Object.assign($config, config);
            // 初始化配置，同一样式只需要配置一次，非必须初始化，有默认配置
            Notice.options = $config;
            return Notice;
        },

        // 查看图片
        viewImage: function (Viewer, galley, url = 'layer-src') {
            if (viewer_flag) {
                viewer.destroy();
            }

            if (galley.length > 0) {
                for (var i = 0; i < galley.length; i++) {
                    viewer = new Viewer(galley[i], {
                        url: url
                    });
                    viewer_flag = true;
                }
            }
        },

        // 查看视频
        viewVideo: function (layer, src) {
            var content = '<div class="video-modal"><div class=""><video class="video-box" src="' + src+ '" autoplay="autoplay" controls="controls"></video></div></div>';
            layer.open({
                title: '查看视频',
                type: 1,
                area: ['600px', '500px'],
                content: content
            });
        },

        // 自定义表单
        ajaxTable: function (layui, url, data, page, limit, table_elm, page_elm) {
            var loading = layer.load(2);
            if (!page) {
                page = 1;
            }
            if (!limit) {
                limit = 20;
            }
            if (!data) {
                data = {};
            }
            if (!table_elm) {
                table_elm = layui.$('.layui-table-box');
            }
            if (!page_elm) {
                page_elm = document.getElementsByClassName('layui-table-page')[0];
            }
            data.page = page;
            data.limit = limit;
            layui.$.post(url, data, function (res) {
                layer.close(loading);
                if (res.code == 0) {
                    table_elm.find('tbody').html(res.html);
                    layui.form.render();
                    // 分页
                    layui.laypage.render({
                        //elem: 'tablePage',
                        elem: page_elm,
                        count: res.count,
                        limit: limit,
                        limits: [10, 20, 50, 100],
                        curr: page,
                        prev: '<i class="layui-icon layui-icon-left"></i>',
                        next: '<i class="layui-icon layui-icon-right"></i>',
                        layout: ['first', 'prev', 'page', 'next', 'last', 'skip', 'count', 'limit'],
                        jump: function (obj, first) {
                            // first（是否首次） -- 首次不执行
                            if (!first) {
                                COMMON.ajaxTable(layui, url, data, obj.curr, obj.limit);
                            }
                        }
                    });
                } else {
                    layer.msg(res.msg);
                }
            })
        },

        // 加载动画
        loading: {
            // 开始显示
            start: function ($, elem, type, opacity, size) {
                var $loading = this.insert($, elem, type, opacity, size);
                $loading.show();
            },
            // 结束显示
            end: function ($, elem, fade, remove) {
                if (elem === undefined) {
                    elem = 'body';
                }
                if (fade === undefined) {
                    fade = true;
                }
                //var $elem = $(elem);
                var $elem = elem;
                var $loading = $elem.children('.page-loading');
                if (remove) {
                    $loading.remove();
                } else if (fade) {
                    $loading.fadeOut('fast');
                } else {
                    $loading.hide();
                }
                $elem.removeClass('page-no-scroll');
            },
            // 插入
            insert: function ($, elem, type, opacity, size) {
                if (elem !== undefined && (typeof elem !== 'string') && !(elem instanceof $)) {
                    type = elem.type;
                    opacity = elem.opacity;
                    size = elem.size;
                    elem = elem.elem;
                }
                if (type === undefined) {
                    type = 1;
                }
                if (size === undefined) {
                    size = 'sm';
                }
                if (elem === undefined) {
                    elem = 'body';
                }
                var loader = [
                    '<div class="layui-loader ' + size + '"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i></div>',
                    '<div class="ball-loader ' + size + '"><span></span><span></span><span></span><span></span></div>',
                    '<div class="signal-loader ' + size + '"><span></span><span></span><span></span><span></span></div>',
                    '<div class="loader-1 ' + size + '"><span></span></div>',
                    '<div class="loader-2 ' + size + '"><span></span></div>'
                ];
                //var $elem = $(elem);
                var $elem = elem;
                $elem.addClass('page-no-scroll');  // 禁用滚动条
                $elem.scrollTop(0);
                var $loading = $elem.children('.page-loading');
                //console.log($loading);
                if ($loading.length <= 0) {
                    $elem.append('<div class="page-loading">' + loader[type] + '</div>');
                    $loading = $elem.children('.page-loading');
                }
                if (opacity !== undefined) {
                    $loading.css('background-color', 'rgba(255,255,255,' + opacity + ')');
                }

                return $loading;
            }
        },
        // loading按钮
        btnLoading: function ($, elem, text, loading) {
            if (text !== undefined && (typeof text === 'boolean')) {
                loading = text;
                text = undefined;
            }
            if (text === undefined) {
                text = '&nbsp;加载中';
            }
            if (loading === undefined) {
                loading = true;
            }
            //var $elem = $(elem);
            var $elem = elem;
            if (loading) {
                $elem.addClass('btn-loading');
                $elem.attr({'data-text': $elem.text()}).empty();
                $elem.prepend('<span class="btn-loading-text"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>' + text + '</span>');
                $elem.attr('disabled', 'disabled').prop('disabled', true);
            } else {
                $elem.removeClass('btn-loading');
                $elem.children('.btn-loading-text').remove();
                $elem.text($elem.attr('data-text')).attr('data-text', '');
                $elem.removeProp('disabled').removeAttr('disabled');
            }
        },
        // 动画数字
        countUp: function ($, elem, isThd, delay, grain) {
            isThd = isThd === null || isThd === undefined || isThd === true || isThd === 'true'; // 是否是千分位
            delay = isNaN(delay) ? 500 : delay; // 动画延迟
            grain = isNaN(grain) ? 100 : grain; // 动画粒度
            var getPref = function (str) {
                var pref = '';
                for (var i = 0; i < str.length; i++) if (!isNaN(str.charAt(i))) return pref; else pref += str.charAt(i);
            }, getSuf = function (str) {
                var suf = '';
                for (var i = str.length - 1; i >= 0; i--) if (!isNaN(str.charAt(i))) return suf; else suf = str.charAt(i) + suf;
            }, toThd = function (num, isThd) {
                if (!isThd) return num;
                if (!/^[0-9]+.?[0-9]*$/.test(num)) return num;
                num = num.toString();
                return num.replace(num.indexOf('.') > 0 ? /(\d)(?=(\d{3})+(?:\.))/g : /(\d)(?=(\d{3})+(?:$))/g, '$1,');
            };
            //var $elem = $(elem);
            var $elem = elem;
            $elem.each(function () {
                var $this = $(this);
                var num = $this.data('num');
                if (!num) {
                    num = $this.text().replace(/,/g, '');  // 内容
                    $this.data('num', num);
                }
                var flag = 'INPUT,TEXTAREA'.indexOf($this.get(0).tagName) >= 0;  // 是否是输入框
                var pref = getPref(num.toString()), suf = getSuf(num.toString());
                var strNum = num.toString().replace(pref, '').replace(suf, '');
                if (isNaN(strNum * 1) || strNum === '0') {
                    flag ? $this.val(num) : $this.html(num);
                    return console.error('not a number');
                }
                var int_dec = strNum.split('.');
                var deciLen = int_dec[1] ? int_dec[1].length : 0;
                var startNum = 0.0, endNum = strNum;
                if (Math.abs(endNum * 1) > 10) startNum = parseFloat(int_dec[0].substring(0, int_dec[0].length - 1) + (int_dec[1] ? '.0' + int_dec[1] : ''));
                var oft = (endNum - startNum) / grain, temp = 0;
                var mTime = setInterval(function () {
                    var str = pref + toThd(startNum.toFixed(deciLen), isThd) + suf;
                    flag ? $this.val(str) : $this.html(str);
                    startNum += oft;
                    temp++;
                    if (Math.abs(startNum) >= Math.abs(endNum * 1) || temp > 5000) {
                        str = pref + toThd(endNum, isThd) + suf;
                        flag ? $this.val(str) : $this.html(str);
                        clearInterval(mTime);
                    }
                }, delay / grain);
            });
        },
    };
}();

Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};
// 删除数组指定的某个元素
Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

// 返回顶部
function go_top() {
    $('body').animate({'scrollTop': 0}, 600);
}

// 判断是否是移动设备
function is_mobile() {
    return navigator.userAgent.match(/iPhone|iPad|iPod|Android|android|BlackBerry|IEMobile/i) ? true : false;
}

// 文件下载
function download_file($, src) {
    /*// 只能下载同源的(本地的文件)，如果是远端跨域的下载不了
    var $a = document.createElement('a');
    $a.setAttribute('href', src);
    $a.setAttribute('download', '');
    var evObj = document.createEvent('MouseEvents');
    evObj.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
    $a.dispatchEvent(evObj);*/

    var url = $('.download_url').val();
    var tempwindow = window.open('_blank');
    //tempwindow.location = url;
    tempwindow.location = url += '?file=' + src;
}

// 验证数据格式
function verify_data(value, type = 'require') {
    var value = value.trim();

    switch (type) {
        // 非空验证
        case 'require':
            return !!value;
            break;
        // 汉字验证
        case 'ecode':
            return /^[^\u4e00-\u9fa5]{0,}$/.test(value);
            break;
        // 手机号验证
        case 'phone':
            //var reg_cn = /^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\d{8}$/;
            return /^1(3|4|5|6|7|8|9)[0-9]\d{8}$/.test(value);
            break;
        // 手机号验证(包含座机)
        case 'phone1':
            return /^400-[0-9]{3}-[0-9]{4}|^800-[0-9]{3}-[0-9]{4}|^1(3|4|5|6|7|8|9)([0-9]{9})|^0[0-9]{2,3}-[0-9]{8}$/.test(value);
            break;
        // 邮箱验证
        case 'email':
            //var reg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
            return /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/.test(value);
            break;
        // 验证非零的正整数
        case 'integer':
            return /^\+?[1-9][0-9]*$/.test(value);
            break;
        // 验证1-10的正数
        case 'number_1_10':
            return /^([1-9]|10)\.?\d*$/.test(value);
            break;
        // 验证正数
        case 'number':
            return /^(([0-9]+[\.]?[0-9]+)|[1-9])$/.test(value);
            break;
        // 验证金额
        case 'money':
            return /^(([1-9]\d*)|\d)(\.\d{1,2})?$/.test(value);
            break;
        // 验证身份证
        case 'identity':
            var reg = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/;
            return reg.test(value);
            break;
        // 验证护照
        case 'passport':
            var reg = /^([PSE]{1}\\d{7}|[GS]{1}\\d{8})$/;
            return reg.test(value);
            break;
        // 验证密码
        case 'password':
            var counter = 0,
                error = '';
            var pass = $.trim(value);
            // 密码强度
            if (pass.match(/\d+/)) {
                counter++;
            }
            if (pass.match(/[a-zA-Z]+/)) {
                counter++;
            }

            if (counter < 2 || pass.match(/[^a-zA-Z0-9]+/)) { // pass.match(/[^a-zA-Z0-9]+/) // 取反，即特殊字符
                error = '至少包含*个字符';
            }
            if (error) {
                return {
                    'status': false,
                    'msg': error
                }
            }
            break;
        // 验证图片格式和大小
        case 'image':
            var fValue = value.toLowerCase();
            //console.log(fValue);
            if (fValue) {
                //if (!/.(jpg|png|gif|jpeg|bmp|tif|tiff|pdf)$/.test(fValue)) {
                if (!/.(jpg|png|gif|jpeg)$/.test(fValue)) {
                    return {
                        'status': false,
                        'msg': '图片类型必须是jpg, png, gif, jpeg, bmp, tif, tiff, pdf中的一种。'
                    }
                }
            }

            // 限制图像的大小为10MB
            var fSize = 1024 * 1024 * 10;
            var fInput = document.getElementById(element);
            var files = fInput.files[0];
            if (files) {
                var size = files.size;
                if (size > fSize) {
                    return false;
                }
            }
            break;
        default: break;
    }

    /*// 非空验证
    if (type == 'require') {
        return !!value;
    }
    // 汉字验证
    if (type === 'ecode') {
        return /^[^\u4e00-\u9fa5]{0,}$/.test(value);
    }
    // 手机号验证
    if (type === 'phone') {
        return /^1(3|4|5|6|7|8|9)[0-9]\d{8}$/.test(value);
    }
    // 手机号验证(包含座机)
    if (type === 'phone1') {
        return /^400-[0-9]{3}-[0-9]{4}|^800-[0-9]{3}-[0-9]{4}|^1(3|4|5|6|7|8|9)([0-9]{9})|^0[0-9]{2,3}-[0-9]{8}$/.test(value);
    }
    // 邮箱验证
    if (type === 'email') {
        return /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/.test(value);
    }
    // 验证非零的正整数
    if (type === 'integer') {
        return /^\+?[1-9][0-9]*$/.test(value);
    }
    // 验证1-10的正数
    if (type === 'number_1_10') {
        return /^([1-9]|10)\.?\d*$/.test(value);
    }
    // 验证正数
    if (type === 'number') {
        return /^(([0-9]+[\.]?[0-9]+)|[1-9])$/.test(value);
    }
    // 验证金额
    if (type === 'money') {
        return /^(([1-9]\d*)|\d)(\.\d{1,2})?$/.test(value);
    }*/
}
